﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using QstkCore.Util;

namespace QstkCore.Domain
{
    public class MarketPrices
    {
        private readonly List<StockPrices> allPrices = new List<StockPrices>();
        private readonly Dictionary<string, int> tickerToIndex = new Dictionary<string, int>();

        public IEnumerable<string> Symbols
        {
            get { return tickerToIndex.Keys; }
        }

        public MarketPrices ReplaceNanFill(FillDirection method)
        {
            foreach (StockPrices stockprices in allPrices)
                stockprices.ReplaceNanFill(method);

            return this;
        }

        private void ReadStock(string dataItem, string symbol, TimeSeries timeSeries)
        {
            try
            {
                StockPrices prices = StockPrices.ReadStock(symbol, dataItem, timeSeries);
                Add(symbol, prices);
            }
            catch (FileNotFoundException)
            {
                Console.WriteLine("  Missing stock data for '" + symbol + "'.  Ignoring.");
            }
        }

        private void Add(string symbol, StockPrices stockPrices)
        {
            tickerToIndex.Add(symbol, allPrices.Count);
            allPrices.Add(stockPrices);
        }

        public static MarketPrices ReadData(IEnumerable<string> symbols,
                                                    string dataItem, TimeSeries timeSeries)
        {
            List<string> symbolsList = symbols.OrderBy(x => x).ToList();
            MarketPrices allData2 = For(symbolsList, dataItem, timeSeries);
            return allData2;
        }

        private static MarketPrices For(IEnumerable<string> symbols, string dataColumnName, TimeSeries timeSeries)
        {
            var r = new MarketPrices();

            Console.WriteLine("Reading market data...");
            Stopwatch stopwatch = Stopwatch.StartNew();

            foreach (string symbol in symbols)
                r.ReadStock(dataColumnName, symbol, timeSeries);
            
            stopwatch.Stop();
            Console.WriteLine("  Elapsed time: " + stopwatch.Elapsed);
            
            return r;
        }

        public float[] ColumnList(string symbol)
        {
            int index;
            if (!tickerToIndex.TryGetValue(symbol, out index))
                return null;

            return allPrices[index].Prices;
        }
    }
}